import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

export interface PhotoSlice {
  keyword: string
  photoData: any,
  category: number,
  start: number,
  categoryName: string
}

const initialState: PhotoSlice = {
  keyword: "清纯",
  photoData: [],
  category: 0,
  start: 0,
  categoryName: ""
}
export const getData = createAsyncThunk("photo/getData", async (payload: any) => {

  const data = await axios.post(
    "http://47.93.31.63:8000/category",
    { count: payload.count, start: payload.start, cid: payload.category }
  );
  return data
})
export const startChange = createAsyncThunk("photo/startChange", async (payload: any) => {
  const { keyword, start, category } = payload

  let data;
  if (keyword) {
    data = await axios.post(
      "http://47.93.31.63:8000/search",
      { count: 24, start: start, kw: keyword }
    );
  } else {
    data = await axios.post(
      "http://47.93.31.63:8000/category",
      { count: 24, start: start, cid: category }
    );
  }
  return data
})


export const photoSlice = createSlice({
  name: 'photo',
  initialState,
  reducers: {
    keywordChange(state, { payload }) {
      state.keyword = payload.keyword; // 内置了immutable
      state.category = 0;
    },
    categoryChange(state, { payload }) {
      state.categoryName = payload.categoryName; // 内置了immutable
      state.category = payload.category;
      state.keyword = "";
    },
    photoDataChange(state, { payload }) {
      state.photoData = payload.payload
    }
  },
  extraReducers: {
    [getData.fulfilled.type]: (state, action: any) => {
      state.photoData = action.payload.data;
      state.category = action.meta.arg.category
      state.categoryName = action.meta.arg.categoryName
      state.start = action.meta.arg.start
    },
    [startChange.fulfilled.type]: (state, action: any) => {

      state.photoData = action.payload.data;
      state.category = action.meta.arg.category
      state.start = action.meta.arg.start
      state.keyword = action.meta.arg.keyword

    }
  }
});

export const { keywordChange, categoryChange, photoDataChange } = photoSlice.actions;



export default photoSlice.reducer;